<template>
  <div>
    <!-- 添加按钮 -->
    <el-button type="primary" @click="dialogVisible = true"
      >添加新用户</el-button
    >
    <!-- 对话框 -->
    <el-dialog
      title="添加新用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="onCloseDialog"
    >
      <el-form
        ref="form"
        :model="form"
        label-width="60px"
        label-position="left"
        :rules="rules"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model.number="form.age"></el-input>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取&nbsp;消</el-button>
        <el-button type="primary" @click="onAddUser">确&nbsp;定</el-button>
      </span>
    </el-dialog>

    <el-table :data="userList" stripe border style="width: 100%">
      <!-- 索引列 -->
      <el-table-column type="index" label="#" />
      <!-- 表格列数据 -->
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="position" label="职位" />
      <!-- 自定义列模板 -->
      <el-table-column prop="addtime" label="创建时间">
        <template #default="scope">
          {{ scope.row.addtime | dateFormat }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <div>
            <router-link :to="'/users/' + row.id">详情</router-link>
            &nbsp;
            <el-link
              icon="el-icon-delete"
              type="danger"
              @click="onDelete(row.id)"
            ></el-link>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: 'MyUserList',
  data() {
    // 自定义年龄校验
    let checkAge = (rule, value, cb) => {
      setTimeout(() => {
        if (value < 18) {
          cb(new Error('必须年满18岁'))
        } else {
          cb()
        }
      })
    }
    return {
      userList: [],
      dialogVisible: false,
      form: {
        name: '',
        age: '',
        position: ''
      },
      // 表单校验规则
      rules: {
        name: [
          {
            type: 'string',
            required: true,
            message: '请输入姓名',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 100,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        age: [
          {
            required: true,
            message: '请输入年龄',
            trigger: 'blur'
          },
          {
            type: 'integer',
            message: '请输入整数',
            trigger: 'blur'
          },
          {
            validator: checkAge,
            trigger: 'blur'
          }
        ],
        position: [
          {
            required: true,
            message: '请输入职位',
            trigger: 'blur'
          },
          {
            required: true,
            type: 'enum',
            message: '请输入正确的职位',
            enum: ['丞相', '始皇帝', '商人', 'admin', 'user', 'guest'],
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.initUserList()
  },
  methods: {
    // 获取用户信息
    async initUserList() {
      const { data: res } = await this.$http.get('/api/users')
      if (res.status !== 0) return this.$message.error('获取用户列表信息失败')
      console.log(res)
      this.userList = res.data
    },
    // 关闭对话框
    onCloseDialog() {
      this.$refs.form.resetFields()
      console.log('ok')
    },
    // 添加用户
    onAddUser() {
      this.$refs.form.validate(async valid => {
        console.log(valid)
        if (!valid) return
        const { data: res } = await this.$http.post('/api/users', this.form)
        console.log(res)
        if (res.status !== 0) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.dialogVisible = false
        this.initUserList()
      })
    },
    // 删除用户
    onDelete(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete('/api/users/' + id)
          console.log(res)
          this.$message.success('删除成功!')
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 10px;
}
</style>
